package etl;

import healpix.essentials.HealpixBase;
import healpix.essentials.Pointing;
import healpix.essentials.Scheme;

import java.io.*;
import java.util.ArrayList;

public class TTHEALPixBRSRCE {
    public static void main(String[] args) throws Exception {

        ArrayList<String> arrayList = new ArrayList<String>();
        long start = System.currentTimeMillis();
        File dir = new File(args[0]);    //读取文件夹
        File[] files = dir.listFiles();//将文件夹中的所有文件读取出来
        BufferedReader br = null;
        BufferedWriter bw = null;

        String shootingTime = "";
        double ra;
        double dec;
        double mag;
        int flag = 1;
        assert files != null;
        long hpx_level_cha = 12-9;

        String outputPath = modifyPath(args[0]);
        createResDirectory(outputPath);
        for (File file : files) {
            if (!file.isDirectory()) {
                br = new BufferedReader(new FileReader(file));
                String data;
                data = br.readLine();
                if (data.startsWith("# obs")) {
                    shootingTime = data.substring((24));
                }
                while ((data = br.readLine()) != null) {
                    if (!data.startsWith("#")) {
                        arrayList.add(data);
                    }

                }

                String parent = file.getParent();
                String chartId = file.getName().substring(17, 21);
                String filename = outputPath+"\\" + chartId + ".txt";
                bw = new BufferedWriter(new FileWriter(filename));
                double pow = Math.pow(2, 12);
                HealpixBase healpixBase = new HealpixBase((long) pow, Scheme.NESTED);
                double HPX_D2R = Math.PI / 180.0;
                double pow2 = Math.pow(2, 9);  // healpix9层级
                HealpixBase healpixBase2 = new HealpixBase((long) pow2, Scheme.NESTED);


                int i = 1;
                for (String s : arrayList) {
                    String[] s1 = s.split("  ");

                    ra = Double.parseDouble(s1[11]);   //赤经
                    dec = Double.parseDouble(s1[12]);  //赤纬
                    mag = Double.parseDouble(s1[16]);  //绝对亮度


                    Pointing ptg = new Pointing((90 - dec) * HPX_D2R, ra * HPX_D2R);
                    long HPXid = healpixBase.ang2pix(ptg);//移位前hpxid
                    long HPXidUP = healpixBase.neighbours(HPXid)[7];//移位后hpxid

                    long newHPXid = HPXid >> (hpx_level_cha * 2);
                    long newHPXidUP = HPXidUP >> (hpx_level_cha * 2);


                    /**
                     * 添加冗余块
                     */
                    String binary = Long.toBinaryString(HPXid);//转换为2进制
                    String lastSixBits = binary.substring(binary.length() - 6);  //提取后6位
                    long HPXid9 = healpixBase2.ang2pix(ptg);
                    if (lastSixBits.equals("010101") || lastSixBits.equals("010100")) {   //证认块上面可能漏源的块
                        long value = healpixBase.neighbours(HPXid9)[6];//移位后hpxid   下面的块
                        bw.write(flag + "," + chartId + "_" + i++  + "," + value + "," + (-1) + "," + ra + "," + dec + "," + mag); // 将 key 和 value 写入 output.txt 文件
                        bw.write("\n");
                    }  else if (lastSixBits.equals("101010") || lastSixBits.equals("101000")){  //证认块左边可能漏源的块
                        long value = healpixBase.neighbours(HPXid9)[0];//移位后hpxid
                        bw.write(flag + "," + chartId + "_" + i++  + "," + value + "," + (-1) + "," + ra + "," + dec + "," + mag); // 将 key 和 value 写入 output.txt 文件
                        bw.write("\n");
                    }



                    int num = Integer.parseInt(lastSixBits,2);
                    int mask1 = 0b101010;
                    int mask2 = 0b010101;
                    int result1 = num & mask1;
                    int result2 = num & mask2;
                    if (Integer.toBinaryString(result1).equals("101010") || Integer.toBinaryString(result1).equals("0")) {
                        bw.write(flag + "," + chartId + "_" + i++ + "," + newHPXid + "," + newHPXidUP + "," + ra + "," + dec + "," + mag);
                        bw.write("\n");
                        continue;
                    } else if (Integer.toBinaryString(result2).equals("10101") || Integer.toBinaryString(result2).equals("0")){
                        bw.write(flag + "," + chartId + "_" + i++ + "," + newHPXid + "," + newHPXidUP + "," + ra + "," + dec + "," + mag);
                        bw.write("\n");
                        continue;
                    }
                    bw.write(flag + "," + chartId + "_" + i++ + "," + newHPXid + "," + (-1) + "," + ra + "," + dec + "," + mag);
                    bw.write("\n");
                }
                System.out.println(filename+"已完成！");
                arrayList.clear();

            }

            flag += 1;
            assert bw != null;
            bw.close();
            br.close();
        }
        long end= System.currentTimeMillis();
        System.out.println("所用时间为："+(end-start)+"毫秒");
        
    }
    public static String modifyPath(String inputPath) {
        File file = new File(inputPath);
        String parentDir = file.getParent();
        String lastFolder = file.getName();
        String newPath = parentDir + "\\res\\" + lastFolder;
        return newPath;
    }
    public static void createResDirectory(String outputPath) {
        File resDir = new File(outputPath);
        if (!resDir.exists()) {
            boolean created = resDir.mkdirs();
            if (created) {
                System.out.println("目录 'res' 和子文件夹已创建: " + outputPath);
            } else {
                System.out.println("创建目录失败!");
            }
        } else {
            System.out.println("目录已存在: " + outputPath);
        }
    }


}
